package com.tangye.massageshop.util;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.tangye.massageshop.entity.UserEntity;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    private static final String KEY = "MASSAGE_SHOP";

    /**
     * 接受业务数据，生成token返回
     * @param claims
     * @return
     */
    public static String getToken(Map<String,Object> claims) {
        return JWT.create().withClaim("claims", claims)
                // 12个小时有效时间
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000*60*60*12))
                .sign(Algorithm.HMAC256(KEY));
    }

    public static String getToken(UserEntity userEntity) {
        Map<String,Object> claims = new HashMap<>();
        claims.put("user", JSON.toJSONString(userEntity));
        return JWT.create().withClaim("claims", claims)
                // 12个小时有效时间
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000*60*60*12))
                .sign(Algorithm.HMAC256(KEY));
    }

    public static Map<String,Object> paresToken(String token) {
        return JWT.require(Algorithm.HMAC256(KEY)).build().verify(token).getClaim("claims").asMap();
    }

    public static UserEntity paresUserToken(String token) {
        String userJson = JWT.require(Algorithm.HMAC256(KEY)).build().verify(token).getClaim("claims").asMap().get("user").toString();
        return JSON.parseObject(userJson, UserEntity.class);
    }
}
